require(['./config'], () => {
    require(['template', 'request', 'header', 'zoom', 'fly'], (template, request, header) => {
      class Detail {
        constructor () {
          this.init()
          this.addToCart()

        console.dir($)
        }
        init () {
          // 取id
          const id = window.location.search.slice(4)
          request.getDetail(id).then(resp => {
            if (resp.code === 200) {
              const { detail } = resp.data
              // console.log(detail)
            
              const {
                id,
                title,
                price,
                originPrice,
                photo,
                saleNum,
                descContentList,
              } = detail
              // 把所有必要的数据统一整理起来，将来模板引擎的传输以及购物车加入的逻辑更加轻量化
              this.detail = {
                id,
                title,
                price,
                photo,
                saleNum,
                descContentList,
              }
              $('#detail-top').html(template('detailJs', {
                ...this.detail
              }))
              // 要等到数据渲染完成以后才能调用放大功能
              this.zoom()
            }
          })
        }
        zoom() {
            // console.log(123)
          $('.zoom-img').elevateZoom({
            gallery: 'gal1',
          })
        }
         
        addToCart() {
            $('.detail-top').on('click', '.addCart', (e) => {
                // console.log($(this))

                // localStorage.setItem('cart', JSON.stringify(this.detail));
                let cart = localStorage.getItem('cart');
                if (cart) {
                    //能拿到cart数据
                    cart = JSON.parse(cart);
                    // console.log(cart);
                    //判断是否存在当前商品
                    const isIdExist = cart.some(shop => {
                        return shop.id === this.detail.id
                     
                    })
                    // console.log(cart)
                    if (isIdExist) {
                        //是否存在存在当前商品
                        cart = cart.map(shop => {
                            if (shop.id === this.detail.id) {
                                shop.num++;
                                return shop;
                              
                            } else {
                                // shop.checkedNum++;
                                return shop;
                            }
                        })
                    } else {
                        cart = cart.map(shop => {
                            shop.checkedNum++;
                            return shop;
                        })
                        cart.push({...this.detail, num: 1, check: true });
                    }
                    localStorage.setItem('cart', JSON.stringify(cart));
                    console.log(cart)
                } else {
                    //没有数据
                    let arr = [{...this.detail, num: 1, check: true, checkedNum: 1 }];
                    localStorage.setItem('cart', JSON.stringify(arr));

                }
                this.fly(e);
            })
        }
        fly(e) {
            const _this = this;
            $(`<img src="${this.detail.photo[0].url}" style="width:20px;height:20px;background:#000;">`).fly({
                start: {
                    left: e.clientX, //开始位置（必填）#fly元素会被设置成position: fixed
                    top: e.clientY, //开始位置（必填）
                },
                end: {
                    left: $('#flycart').offset().left, //结束位置（必填）
                    top: $('#flycart').offset().top - $(window).scrollTop(), //结束位置（必填）
                },
                autoPlay: true, //是否直接运动,默认true
                speed: 1.0, //越大越快，默认1.2
                vertex_Rtop: 100, //运动轨迹最高点top值，默认20
                onEnd: function() {
                        // console.log('222');
                        this.destroy(); //移除dom
                        _this.showCartTotalNum();
                    } //结束回调
            });
        }
        showCartTotalNum() {
            // console.log('showCartTotalNum')
            let num = 0;
            let cart = localStorage.getItem('cart');
            if (cart) {
                cart = JSON.parse(cart);
                num = cart.reduce((res, goods) => {
                        res += goods.num;
                        return res
                    }, 0)
                    // console.log('num===',cart,num,$('#shopNum'))
                $('#cart-item-num').html(num)
            }
        }


        }
        new Detail();
    })

})